package com.dst.smart.service;

import java.util.ArrayList;
import java.util.List;
import java.util.Random;

import com.dst.smart.app.MyApplication;
import com.dst.smart.app.MainActivity;
import com.dst.smart.dao.impl.factory.GateWayFactory;
import com.dst.smart.json.ProjectUtils;
import com.dst.smart.model.GateWay;
import com.dst.smart.socket.info.ISocketCode;

public class TcpSender {
	public static String deviceID = "";
	private static int iSerial = 0;
	private static int iSRandom = 0;
	public static void sendMssageAF(int fromSource,String message) {
		try {

			if (message == null) {
				return;
			}
			if (!"".equals(message)) {
//				if (message.equals("*C0019A0A30000AAA90A0000")) {
//					MainActivity.playSound(1,"嗨!主人我在這呢.");
//				}else{
//					if(message.length()>25) {
//						if (message.substring(0, 6).equals("*C0032")) {
//							SendCMD.blackCode(message);
//						}
//					}
//				}
//				String TampStr = message + "3";
//				byte[] data = new byte[TampStr.length()];
//				data = TampStr.getBytes();
//				data[TampStr.length() - 1] = 13;
//				MyApplication.getInstance().SendDate(data);
////				[42, 67, 49, 48, 48, 57, 65, 48, 48, 67, 48, 48, 51, 50, 48, 51, 48, 48, 48, 49, 50, 48, 48, 49, 51, 57, 13]
////				[42, 67, 49, 48, 48, 57, 65, 48, 48, 49, 48, 48, 57, 53, 48, 48, 48, 48, 48, 49, 50, 48, 48, 52, 51, 55, 13]
////				HomeFragment.setCode("serialSend:" + TampStr);
				//透過其他网関
				String TampStr = message;
				String SmartHomeStr = message;
				String s = message.substring(0, 2);
				if(fromSource<2) {
					Boolean IsSendFlag = false;
					if(fromSource==0) {
						int edition =1;
						int getwayCount = 0;
						if (edition == 1) {
							List<GateWay> list = GateWayFactory.getAll();  //joe
							for (GateWay oldGateway : list) {
								if (oldGateway.getSeqencing() == 0) { //joe
									getwayCount++;
								}
							}
						}
						if ((edition == 0) || (getwayCount > 0)) {
							s = message.substring(0, 2);
							if (s.equals("*C")) {
								if (getwayCount > 0) {
									edition = 1;
								}
								if (iSRandom == 0) {
									iSRandom = (new Random().nextInt(255) % 255) + 1;
								}
								iSerial++;
								if (iSerial > 255) {
									iSerial = 0;
								}
								String s1 = toHex(iSRandom);
								SmartHomeStr = TampStr.substring(0, 2) + s1
										+ TampStr.substring(4) + toHex(iSerial);
								String s2 = toHex(iSerial ^ 0x000f);
								// TampStr加密給攝像頭网關
								TampStr = TampStr.substring(0, 2) + s1
										+ TampStr.substring(4) + s2;
							} else {
								edition = 1;
							}
						}
					}else {
						if (message.equals("*C0019FA1C000000A90A0000")) {
							MainActivity.playSound(1, "嗨!主人我在這呢.");
							IsSendFlag = false;
						} else {
							if (message.length() > 25) {
								if (message.substring(0, 6).equals("*C0032")) {
									SendCMD.blackCode(message);
								}
							}
						}
					}
					TampStr = TampStr + "3";
					if (message.equals("*D0")) {
						IsSendFlag = true;
					} else {
						if (s.equals("*C")) {
							s = message.substring(4, 6);
							String tempType = message.substring(8, 10);
							if (((s.equals("09") || s.equals("19")) && !tempType.equals("07"))
									|| s.equals("32") || s.equals("0A")) {
								IsSendFlag = true;
							}
						}
					}
					if (IsSendFlag) {
						List<GateWay> gateWayList = GateWayFactory.getAll();
						for (int i = 0; i < gateWayList.size(); i++) {
							GateWay gateway = gateWayList.get(i);
							int gatewayTypeID = gateway.getTypeId();
							//if (gateway.getIsCurrent() > 0) {
							if (gateway.getSeqencing() ==1) { //joe
							    /*
                                if (gatewayTypeID <= 2) {
                                    // && [gateway.currentGateway integerValue] > 0
                                    int userID = Integer.parseInt(GateWayService.mp
                                            .get(gateway.getGatewayID()));
                                    //TampStr = TampStr + "3";
                                    byte[] data = new byte[TampStr.length()];
                                    data = TampStr.getBytes();
                                    data[TampStr.length() - 1] = (byte) ((edition == 1) ? 3
                                            : 10);
                                    String cmd = "";
                                    for (int j = 0; j < TampStr.length(); j++) {
                                        if (edition == 0) {
                                            if ((j > 1) && (j < (TampStr.length() - 2))) {
                                                data[j] = (byte) (data[j] ^ (iSerial & 0x000f));
                                            }
                                        }
                                        cmd = cmd
                                                + Integer.toHexString(data[j] / 16)
                                                .toUpperCase()
                                                + Integer.toHexString(data[j] % 16)
                                                .toUpperCase();
                                    }
                                    int result = DeviceSDK.setDeviceParam(userID,
                                            0x2725, cmd);
                                } else
							    */
								if ((gatewayTypeID == 1) || (gatewayTypeID == 2)) {
									Thread.sleep(50);
									String deviceID = gateway.getGatewayID();
									String result = ISocketCode.setForward(SmartHomeStr,
											deviceID);
									MainActivity.activity.sendCode(result);
								}
							}
						}
					}
				}
				//串口通訊
				//String TampStr = message + "3";
				TampStr = SmartHomeStr + "3";
				byte[] data = new byte[TampStr.length()];
				data = TampStr.getBytes();
				data[TampStr.length() - 1] = 13;
				MyApplication.getInstance().SendDate(data);
			}
			//	*C1019AA020022AA1000300445
//			[42, 67, 49, 48, 49, 57, 65, 65, 48, 50, 48, 48, 50, 50, 65, 65, 49, 48, 48, 48, 51, 48, 48, 52, 52, 53, 13]
		} catch (Exception e) {
			e.printStackTrace();
		}
	}

	public static String toHex(int number) {
		return ( ((number <= 15)?"0":"") + Integer.toHexString(number).toUpperCase());
	}

	public static void dataProcess(String data) {
		// *d0100242001=00,05
		String[] arrys = data.split("");
		if (arrys.length > 0) {
			String string = arrys[0];
			if (string.length() > 2) {
				// 回碼長度不足必?氂绣e誤?幚肀?護!
				String CommandType = string.substring(0, 2);
				if ("*C".equals(CommandType)) { // 標準指令
					// *C0019AA010000AA0000000000
					CommandType = string.substring(4, 6);
					if ("00".equals(CommandType)) { // 數字量回碼
					} else if ("01".equals(CommandType)) { // 數字量位元回碼
					} else if ("02".equals(CommandType)) { // (保留)
					} else if ("03".equals(CommandType)) { // 多筆模擬量回碼
						//*C00 03 24 FF 00 ID 00 00 00 00 00
						String Type = string.substring(6, 8);
						if ("24".equals(Type)){
							String deviceId=string.substring(12, 14)+string.substring(20, 24);
							String SubCommand = string.substring(15, 16);
							if ("0".equals(SubCommand)) { // 溫濕度
								Integer Temperature = Integer.valueOf(
										string.substring(16, 18), 16);
								Integer Humidity = Integer.valueOf(
										string.substring(18, 20), 16);
								String SaveDevice=ProjectUtils.getRootPath().getAirQuality();
								String[] deviceData=SaveDevice.split(",");
								for(int index=0;index<deviceData.length;index++) {
									if(deviceData[index].equals(deviceId)) {
										MainActivity.insideTemp[index] = (Temperature - 20);
										MainActivity.Humidity[index] = Humidity;
									}
								}
							} else if ("1".equals(SubCommand)) { // PM2.5
								Integer PM2_5 = Integer.valueOf(
										string.substring(16, 20), 16);
								String SaveDevice=ProjectUtils.getRootPath().getAirQuality();
								String[] deviceData=SaveDevice.split(",");
								for(int index=0;index<deviceData.length;index++) {
									if(deviceData[index].equals(deviceId)) {
										MainActivity.pm25[index] = PM2_5;
									}
								}
							} else if ("2".equals(SubCommand)) { // 甲醛
								Integer formaldehyde = Integer.valueOf(
										string.substring(16, 20), 16);
								String SaveDevice=ProjectUtils.getRootPath().getAirQuality();
								String[] deviceData=SaveDevice.split(",");
								for(int index=0;index<deviceData.length;index++) {
									if(deviceData[index].equals(deviceId)) {
										MainActivity.formaldehyde[index] = formaldehyde;
									}
								}
							} else if ("3".equals(SubCommand)) { // 照度
								int illumination = Integer.valueOf(
										string.substring(16, 20), 16);
								String SaveDevice=ProjectUtils.getRootPath().getIllumination();
								String[] deviceData=SaveDevice.split(",");
								for(int index=0;index<deviceData.length;index++) {
									if(deviceData[index].equals(deviceId)) {
										MainActivity.illumination[index] = illumination;
									}
								}
							} else if ("4".equals(SubCommand)) { // 人數
								int NumberOfPeople = Integer.valueOf(
										string.substring(16, 20), 16);
								String SaveDevice=ProjectUtils.getRootPath().getIllumination();
								String[] deviceData=SaveDevice.split(",");
								for(int index=0;index<deviceData.length;index++) {
									if(deviceData[index].equals(deviceId)) {
										MainActivity.NumberOfPeople = NumberOfPeople;
									}
								}
							}
						}
					} else if ("04".equals(CommandType)) { // 單筆模擬量回碼
						// 紅外設備?娏?偵測回碼

					} else if ("12".equals(CommandType)) { // 查?冊O備回碼
						String SubCommand = string.substring(14, 16);
						if ("01".equals(SubCommand)) { // 讀取內存數據

						} else if ("02".equals(SubCommand)) { // 讀取設備?愋?
							// getDeviceState(string, 3);
						}
					} else if ("19".equals(CommandType)) { // 控制指令

					} else if ("32".equals(CommandType)) { // 情景指令
						SendCMD.blackCode(data);
					} else if ("1C".equals(CommandType)) { // 中繼路由表

					} else if ("1D".equals(CommandType)) { // 中繼指令

					} else if ("81".equals(CommandType)) { // 門??來?娭噶?

					} else if ("15".equals(CommandType)) { // 讀取智能報警狀態

					} else if ("65".equals(CommandType)) { // 安防報警

					} else if ("1F".equals(CommandType)) { // 通訊模式
						String Type = string.substring(6, 8);
						if ("24".equals(Type)){
							if(MainActivity.addSensorTime>0){
								//*C001F24FF00000000000000
								String deviceID=string.substring(18, 24);
								if((MainActivity.addSensorId & 0x0010)>0){
									String SaveDevice = ProjectUtils.getRootPath().getIllumination();
									String[] deviceData = SaveDevice.split(",");
									int index=MainActivity.addSensorId-16;
									if(index<deviceData.length) {
										deviceData[index] = deviceID;
										String saveDeviceID = "";
										for (int i = 0; i < deviceData.length; i++) {
											saveDeviceID += deviceData[i] + ",";
										}
										ProjectUtils.getRootPath().setIllumination(saveDeviceID);
										ProjectUtils.saveRootPath();
									}
								}else {
									String SaveDevice = ProjectUtils.getRootPath().getAirQuality();
									String[] deviceData = SaveDevice.split(",");
									int index=MainActivity.addSensorId;
									if(index<deviceData.length) {
										deviceData[index] = deviceID;
										String saveDeviceID = "";
										for (int i = 0; i < deviceData.length; i++) {
											saveDeviceID += deviceData[i] + ",";
										}
										ProjectUtils.getRootPath().setAirQuality(saveDeviceID);
										ProjectUtils.saveRootPath();
									}
								}
								MainActivity.playSound(5, "传感器配對成功");
								MainActivity.addSensorTime=0;
							}
						}
					}
				} else if ("*T".equals(CommandType)) { // 定時指令回碼
					// 增加判斷是否本機查?儾奴@取此?嵪?
					// SendCMD.blackCode(data);
				} else if ("*M".equals(CommandType)) { // 情景指令回碼
					// 增加判斷是否本機查?儾奴@取此?嵪?

				} else if ("*c".equals(CommandType)) { // 精?喼噶疃喙P模擬量回碼:空調,背景音樂....等
					// *c003000010000=00,00,00(03)
					// 4,5:type 8,9:ID 10,11:mid1 12,13:mid2
					// getDeviceState(string, 2);
					SendCMD.blackCode(data);
					// [self getLearnDevice:string andIndex:0];
				} else if ("*d".equals(CommandType)) { // 精?喼噶?數字量回碼:燈光,插座....等
					// *d003000010000=00,00(03)
					// 4,5:type 8,9:ID 10,11:mid1 12,13:mid2
					// getDeviceState(string, 0);
					SendCMD.blackCode(data);
					// [self getLearnDevice:string andIndex:0];
				} else if ("*a".equals(CommandType)) { // 精?喼噶?單筆模擬量回碼:調光數值
					// *d000300010000=100(03)
					SendCMD.blackCode(data);
					// getDeviceState(string, 1);
					// [self getLearnDevice:string andIndex:0];
				} else if ("*r".equals(CommandType)) { // 紅外?學?暢晒卮a
					// *r00050001=100(03)
					/*
					 * //增加判斷是否本機進入紅外學?暡奴@取此?嵪? if (string.length > 4) {
					 * NSString *s =[string substringWithRange:NSMakeRange(2,
					 * 2)]; if([s.equals(@"05")){ NSString *prams = [string
					 * substringFromIndex:11]; //[DSTAlertView
					 * showMessage:[NSString
					 * stringWithFormat:@"红外线学习成功，长度:%@",prams]]; } }
					 */
				} else if ("*I".equals(CommandType)) { // 背景音樂或紅外?學?暬卮a

					// analysisInfrared_code(string);
				} else if ("*m".equals(CommandType)) { // 模組場景代碼
					// *m00030001=FFh(03)
				} else if ("*Z".equals(CommandType)) { // い??


				} else if ("*t".equals(CommandType)) {
					SendCMD.blackCode(data);

				} else if ("#E".equals(string)) {

				} else {
					// 是否需特別?幚碇噶?

				}
			}
			// [[NSNotificationCenter
			// defaultCenter]postNotificationName:kReloadDataDevice object:nil];

		}

	}

	static String[] _songCode = new String[8];
	static String _studyCode = "";

	public static void analysisInfrared_code(String string) {

		Integer index = Integer.valueOf(string.substring(6, 8), 16);
		//Integer len = Integer.valueOf(string.substring(8, 10), 16);
		Integer number = Integer.valueOf(string.substring(18, 20), 16);
		if (index == 255) {

			int i = 0;
			for (; i < _songCode.length; i++) {
				String sss = _songCode[i];
				if (sss.length() > 0) {
					_studyCode += sss;
				} else {
					break;
				}
			}

			if (_studyCode.length() > 3
					&& (((number == i) && (number > 0)) || (number == 0))) {
				// restulBlock(_studyCode);
			}
		} else {
			if (index == 0) {
				_songCode = new String[8];
				_studyCode = "";
			}
			// [_songCode addObject:[string substringWithRange:NSMakeRange(10,
			// 2*len)]];
		}
	}

}
